package com.xuelang.pipeline.worker.app.crd.application.impl;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.xuelang.pipeline.worker.app.common.util.K8sUtils;
import com.xuelang.pipeline.worker.app.common.util.OffsetDateTimeAdapter;
import com.xuelang.pipeline.worker.app.crd.application.ApplicationService;
import com.xuelang.pipeline.worker.client.common.result.ApiResult;
import com.xuelang.pipeline.worker.client.crd.dto.ApplicationDTO;
import com.xuelang.pipeline.worker.client.crd.models.V1beta1Application;
import com.xuelang.pipeline.worker.client.crd.models.V1beta1ApplicationList;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CustomObjectsApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Type;
import java.time.OffsetDateTime;

/**
 * @author liuyuan.ly
 * @since 2024/7/26 9:59
 */
@Service
@Slf4j
public class ApplicationServiceImpl implements ApplicationService {


    @Override
    public ApiResult<Boolean> saveOrUpdateApplication(ApplicationDTO dto) {

        System.out.println(JSON.toJSONString(dto.getV1beta1Application()));
        V1beta1ApplicationList v1beta1ApplicationList = getApplicationList(dto);
        K8sUtils.initApiClient(dto.getKubeConfig());
        CustomObjectsApi customObjectsApi = new CustomObjectsApi();
        Object object = null;
        try {
            if (CollectionUtils.isEmpty(v1beta1ApplicationList.getItems())) {
                //未查询到则创建，无则更新
                object = customObjectsApi.createNamespacedCustomObject(
                        "core.oam.dev",
                        "v1beta1",
                        dto.getNamespaceName(),
                        "applications",
                        dto.getV1beta1Application(), null, null, null
                );
            } else {

                V1beta1Application updateApplication = v1beta1ApplicationList.getItems().get(0);
                updateApplication.setSpec(dto.getV1beta1Application().getSpec());
                object = customObjectsApi.replaceNamespacedCustomObject(
                        "core.oam.dev",
                        "v1beta1",
                        dto.getNamespaceName(),
                        "applications",
                        updateApplication.getMetadata().getName(),
                        updateApplication,
                        null,
                        null
                );
            }
        } catch (ApiException e) {
            log.info("application:{}创建失败\napi返回信息:{},堆栈信息:", e.getResponseBody(), e);
            throw new RuntimeException(e.getResponseBody());
        }

        return ApiResult.success(true);
    }

//    private V1beta1Application getApplication() {
//        V1beta1Application v1beta1Application = new V1beta1Application();
//        v1beta1Application.setApiVersion("core.oam.dev/v1beta1");
//        v1beta1Application.setKind("Application");
//        V1ObjectMeta v1ObjectMeta = new V1ObjectMeta();
//        v1ObjectMeta.setName("mts");
//        v1ObjectMeta.setNamespace("default");
//        v1beta1Application.setMetadata(v1ObjectMeta);
//        V1beta1ApplicationSpec spec = new V1beta1ApplicationSpec();
//        List<V1beta1ApplicationSpecComponents> componentsList = new ArrayList<>();
//        V1beta1ApplicationSpecComponents components = new V1beta1ApplicationSpecComponents();
//        components.setName("mts-component");
//        components.setType("webservice");
//        HashMap hashMap = new HashMap();
//        hashMap.put("image", "registry.xuelangyun.com/shuzhi/simple-web-demo:v1");
//        components.setProperties(hashMap);
//
//        V1beta1ApplicationSpecTraits scaler = new V1beta1ApplicationSpecTraits();
//        scaler.setType("scaler");
//        HashMap scalerHashMap = new HashMap();
//        scalerHashMap.put("replicas", 1);
//        scaler.setProperties(scalerHashMap);
////
////
////        V1beta1ApplicationSpecTraits gateway = new V1beta1ApplicationSpecTraits();;
////        scaler.setType("gateway");
//        scaler.setProperties(scalerHashMap);
//
//
//        List<V1beta1ApplicationSpecTraits> traitList = new ArrayList<>();
//        traitList.add(scaler);
//        components.setTraits(traitList);
//        componentsList.add(components);
//        spec.setComponents(componentsList);
//        v1beta1Application.setSpec(spec);
//
//        return v1beta1Application;
//    }

    @Override
    public V1beta1ApplicationList getApplicationList(ApplicationDTO dto) {

        K8sUtils.initApiClient(dto.getKubeConfig());
        CustomObjectsApi customObjectsApi = new CustomObjectsApi();
        V1beta1ApplicationList v1beta1ApplicationList = new V1beta1ApplicationList();
        String filedName = "";
        if (!StringUtils.isBlank(dto.getApplicationName())) {
            filedName = "metadata.name=" + dto.getApplicationName();
        }
        try {
            Object o = customObjectsApi.listNamespacedCustomObject(
                    "core.oam.dev", "v1beta1", dto.getNamespaceName(),
                    "applications", null, null, null,
                    filedName, null,
                    null, null, null, null, null);


            Gson gson = new GsonBuilder()
                    .registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeAdapter())
                    .create();
            String json = gson.toJson(o);
            Type listType = new TypeToken<V1beta1ApplicationList>() {
            }.getType();
            v1beta1ApplicationList = gson.fromJson(json, listType);
        } catch (ApiException e) {
            log.info("获取Application信息失败\napi返回信息:{},堆栈信息:", e.getResponseBody(), e);
            throw new RuntimeException(e.getResponseBody());
        }
        return v1beta1ApplicationList;

    }


}
